﻿using System;
using System.Linq.Expressions;
using System.Reflection;

namespace HY.Common
{
    /// <summary>
    /// 属性扩展类
    /// </summary>
    public static class PropertySupport
    {
        /// <summary>
        /// 获取拉姆达表达式中属性列的字符串形式
        /// </summary>
        /// <typeparam name="T">实体</typeparam>
        /// <param name="propertyExpression">拉姆达表达式</param>
        /// <returns></returns>
        public static string GetPropertyName<T>(Expression<Func<T, object>> propertyExpression)
        {
            LambdaExpression lambda = (LambdaExpression)propertyExpression;
            MemberExpression memberExpression;
            if (lambda.Body is MethodCallExpression)
            {
                var methodCallExpression = (MethodCallExpression)lambda.Body;
                return methodCallExpression.Method.Name;
            }
            if (lambda.Body is UnaryExpression)
            {
                UnaryExpression unaryExpression = (UnaryExpression)(lambda.Body);
                memberExpression = (MemberExpression)(unaryExpression.Operand);
            }
            else
            {
                memberExpression = (MemberExpression)(lambda.Body);
            }
            return ((PropertyInfo)memberExpression.Member).Name;
        }
    }

}
